﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using NetFluid;
using NetFluid.Debug;
using Sito.Model;

namespace Sito.Logic
{
    [Route("assistance")]
    class TrackerManager:FluidPage
    {
        [Route("submit")]
        public void Submit(string description,  Bug.BugPriority priority)
        {
            if(description!=null)
            {
                description = description.StripHTML().Trim();
                if(!string.IsNullOrEmpty(description))
                {
                    var b = new Bug
                    {
                        AssignedTo = "",
                        Guid = Guid.NewGuid().ToString(),
                        Author = session("User") != null ? session("User").NiceName : "Anonymous",
                        Changes = new string[0],
                        Date = DateTime.Now,
                        Description = description,
                        Priority = priority,
                        Status = Bug.BugStatus.Assigning
                    };
                    Database.Bug.Save(b);
                    render("Sito.View.Tracker.List", Database.Bug.FindAll());
                    return;
                }
            }
            render("Sito.View.Tracker.Submit");
        }

        [Route("view")]
        public void View(string id)
        {
            var bg = Database.Bug.Find(Query.EQ("Guid", id));

            if(bg.Count()>0)
            {
                var tick = bg.First();
                render("Sito.View.Tracker.ViewBug",tick);
                return;
            }
            render("Sito.View.Block","Not Found");
        }

        [Route("change")]
        public void Change(string guid, Bug.BugPriority priority, Bug.BugStatus status, string assignedto)
        {
            var bg = Database.Bug.Find(Query.EQ("Guid", guid));

            if (bg.Count() > 0)
            {
                var b = bg.First();
                b.Priority = priority;
                b.Status = status;
                b.AssignedTo = assignedto;

                Database.News.Update(Query.EQ("Guid", guid), Update.Replace(b));
                View(guid);
            }
            render("Sito.View.Block", "Not Found");
        }

        public override void Main()
        {
            render("Sito.View.Tracker.List",Database.Bug.FindAll());
        }
    }
}
